package com.github.catvod.spider;

import android.content.Context;

import com.github.catvod.bean.Class;
import com.github.catvod.bean.Result;
import com.github.catvod.bean.Vod;
import com.github.catvod.crawler.Spider;
import com.github.catvod.crawler.SpiderDebug;
import com.github.catvod.net.OkHttp;
import com.github.catvod.utils.Notify;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AvDog extends Spider {
    private static String siteUrl;
    private String categoryUrl=siteUrl+"data/getlistbyid";
    private String playUrl="https://vdo.sinw.net/m3u8/";
    private String picUrl ="https://img.sinw.net/";
    private final String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";


    // 配置初始化,防治域名时刻变化
    @Override
    public void init(Context context, String extend) throws Exception {
        // 请求最新域名
        this.siteUrl = get_field_name();
        Notify.show("自动进行换源啦~放心看~");
        System.out.println("最新域名："+this.siteUrl);
    }

    /**
     * 获取请求头
     * @param referer
     * @return
     */
    private Map<String, String> getHeader(String referer) {
        Map<String, String> header = new HashMap<>();
        header.put("User-Agent", userAgent);
        header.put("Referer", referer);
        header.put("accept-language", "zh-CN,zh;q=0.9");
        header.put("sec-fetch-mode", "cors");
        return header;
    }


    // 请求拦截器
    private String req(String url, String body,Map<String, String> header) throws Exception {
        Request.Builder builder = new Request.Builder().post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), body)).url(url);
        for (String key : header.keySet()) builder.addHeader(key, header.get(key));
        Request request = builder.build();
        return req(request);
    }
    // get请求
    private String req(String url, Map<String, String> header) {
        return OkHttp.string(url, header);
    }
    // 请求
    private String req(Request request) throws Exception {
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response = okHttpClient.newCall(request).execute();
        return req(response);
    }

    /**
     * 响应拦截器
     * @param response
     * @return
     * @throws Exception
     */
    private String req(Response response) throws Exception {
        if (!response.isSuccessful()) return "";
        byte[] bytes = response.body().bytes();
        response.close();
        return new String(bytes, "UTF-8");
    }

    /**
     * 获取最新域名
     * @return
     */
    private String get_field_name() throws IOException {
        String req = req("https://avdog.net/",  getHeader(""));
        String result = find(req);
        String regex="<p onclick=\"go\\('([^']*)'\\)\">";
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(result);
        String url=m.find()?"https://"+m.group(1):"";
        // 获取重定向最新域名url
        // 构建请求对象
        Request request = new Request.Builder().get().url(url).build();
        OkHttpClient okHttpClient = new OkHttpClient();
        // 执行请求
        Response response = okHttpClient.newCall(request).execute();
        // 进行返回获取到的重定向的url
        return response.request().url().toString();
    }

    /**
     * 匹配网页html
     * @param html
     * @return
     */
    private String find(String html) {
        String regex = "<script>document.write\\(decodeURIComponent\\((.*)\\)\\)</script>";
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(html);
        return m.find() ? URLDecoder.decode(m.group(1)).trim() : "";
    }

    // 首页导航栏
    @Override
    public String homeContent(boolean filter) throws Exception {
        List<com.github.catvod.bean.Class> classes = new ArrayList<>();
        List<String> typeIds = Arrays.asList("/category/7", "/category/8", "/category/5", "/category/6", "/category/11", "/category/14", "/category/12", "/category/13", "/category/15", "/category/16", "/category/18", "/category/48", "/category/19", "/category/21", "/category/22", "/category/20");
        List<String> typeNames = Arrays.asList("大厂原创", "重磅泄密", "偷拍自拍", "绿帽偷情", "中文字幕", "强奸迷奸", "高清无码", "熟女人妻", "剧情大片", "黑白配", "美颜巨乳", "欧美少妇", "动漫3D", "网红主播", "AI换脸", "女同男同");
        for (int i = 0; i < typeIds.size(); i++) {
            classes.add(new Class(typeIds.get(i), typeNames.get(i)));
        }
        System.out.println(siteUrl);
        List<Vod> list = new ArrayList<>();
        return Result.string(classes,list);
    }

    private List<Vod> parseHtml(Document document){
        Elements video_list = document.select(".videolist a");
        List<Vod> videos = new ArrayList<>();
        for (Element a : video_list) {
            String url = a.attr("href");
            String title = a.select(".title").text().strip().replace("\n", "");
            String pic = a.select("img").attr("data-original");
            videos.add(new Vod(url, title, pic));
        }
        return videos;
    }

    /**
     * 影片分类内容
     * @param tid    影片分类id值，来自 homeContent 里面的 type_id 值
     * @param pg     第几页
     * @param filter 暂时不用
     * @param extend 用户已经选择的二级筛选数据
     * @return
     * @throws Exception
     */
    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) throws Exception {
        // 进行去除域名最后的/
        String categoryUrl="";
        if (this.siteUrl.endsWith("/")){
            categoryUrl= this.siteUrl.substring(0, this.siteUrl.length() - 1)+tid+"/"+pg+"/";;
        }else {
            categoryUrl= this.siteUrl+tid+"/"+pg+"/";
        }
        System.out.println(categoryUrl);
        String string = OkHttp.string(categoryUrl, getHeader(categoryUrl));
        String html_str = find(string);
        Document html = Jsoup.parse(html_str);
        List<Vod> list = parseHtml(html);
        Integer total = (Integer.parseInt(pg) + 1) * 30;
        return Result.string(Integer.parseInt(pg), Integer.parseInt(pg) + 1, 10, total, list);
    }


    /**
     * 搜索内容:TODO:搜索分页无法使用,后续优化
     * @param key
     * @param quick
     * @return
     * @throws Exception
     */
    @Override
    public String searchContent(String key, boolean quick) throws Exception {
        // 对关键字进行URL编码
        // 防治不能用:
        String fieldName = get_field_name();
        String searchUrl = fieldName+"search/"+ URLEncoder.encode(key) +"/";
        String string = OkHttp.string(searchUrl, getHeader(siteUrl));
        String html_str = find(string);;
        Document doc = Jsoup.parse(html_str);
        List<Vod> list = parseHtml(doc);
        return Result.string(list);
    }

    /**
     * 影片详情
     * @param ids ids.get(0) 来源于 categoryContent() 或 searchContent() 的 vod_id
     * @return
     * @throws Exception
     */
    @Override
    public String detailContent(List<String> ids) throws Exception {
        String vod_id = ids.get(0);
        String datail_url=siteUrl+vod_id.substring(1);
        System.out.println(datail_url);
        if (siteUrl ==null|| siteUrl.isBlank()){
            siteUrl = get_field_name();
            datail_url = siteUrl +vod_id;
        }
        String response = req(datail_url, getHeader(siteUrl));
        String html = find(response);
        Document doc = Jsoup.parse(html);
        String title = doc.select("p#title").text();
        // 进行匹配播放m3u8链接
        String regex = "initPlayer\\(\"(.*)\"\\)";
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(html);
        String m3u8 = m.find() ? m.group(1) : "";
        // 进行拼接播放的m3u8
        String play_url = playUrl + m3u8;
        Vod vod = new Vod();
        vod.setVodId(vod_id);
        vod.setVodName(title);
        vod.setVodPlayFrom("m3u8");
        vod.setVodPlayUrl("播放$"+play_url);
        return Result.string(vod);
    };


    /**
     * 播放页
     * @param flag 来源于 detailContent() 里面的 vod_play_from线路
     * @param id   播放页链接或直链 来源于 detailContent 里面的 vod_play_url 选集
     * @param vipFlags 是否需要进行解析播放
     * @return
     * @throws Exception
     */
    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) throws Exception {
        return Result.get().url(id).header(getHeader(siteUrl)).string();
    }
}
